import { Login, queryUserProfile } from '../../api/user'
import { Commit } from 'vuex'
import { ElMessage } from 'element-plus'

interface UserState {
  userId: number
  nickname: string
  avatar: string
}

// user.module.ts

const userModule = {
  state: (): UserState => ({
    userId: 0,
    nickname: '',
    avatar: ''
  }),
  mutations: {
    SET_USER_ID(state: UserState, userId: number) {
      state.userId = userId
    },
    SET_NICKNAME(state: UserState, nickname: string) {
      state.nickname = nickname
    },
    SET_AVATAR(state: UserState, avatar: string) {
      state.avatar = avatar
    }
  },
  actions: {
    async LoginUser(
      { commit }: { commit: Commit },
      loginForm: { username: string; password: string }
    ) {
      try {
        const res: any = await Login(loginForm.username, loginForm.password)
        if (res.code === 200) {
          ElMessage.success(res.msg)
          commit('SET_USER_ID', res.data.userId)
          commit('SET_NICKNAME', res.data.nickname)
          commit('SET_AVATAR', res.data.avatar)
          window.electron.ipcRenderer.send('change-window-size', [1000, 700])
        }
      } catch (error) {
        throw error
      }
    },

    UpdateLoginUser({ commit }: { commit: Commit }, userId: number) {
      queryUserProfile(userId).then((res: any) => {
        if (res.code === 200) {
          commit('SET_USER_ID', res.data.userId)
          commit('SET_NICKNAME', res.data.nickname)
          commit('SET_AVATAR', res.data.avatar)
        }
      })
    }
  },
  getters: {
    getUserId: (state: UserState) => state.userId,
    getUserNickname: (state: UserState) => state.nickname,
    getUserAvatar: (state: UserState) => state.avatar
  }
}

export default userModule
